package org.fintan.make.controller;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.servlet.http.HttpServletRequest;

import org.fintan.make.master.ExecuteResult;
import org.fintan.make.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

import io.swagger.annotations.Api;

//@RefreshScope
@Api(description = "图片上传接口接口文档")
@Controller
@RequestMapping(value = "/picture")
// @ConfigurationProperties(prefix = "oss")
public class OssController {
	Logger logger = LoggerFactory.getLogger(getClass());
	// 图片保存路径
	// private String path = "/opt/study/image/";
	@Value("${path.image:havefun.tech:8089/root/opt/study/image/}")
	private String path;

	@Value("${unipock.oss.accessKeyId:Sq3VArArISFZolo3}")
	private String accessKeyId;
	@Value("${unipock.oss.accessKeySecret:jCqkj9xOyQhccha2GmeHVZcNaIOtix}")
	private String accessKeySecret;
	@Value("${unipock.oss.endPoint:oss-cn-shenzhen.aliyuncs.com}")
	private String endPoint;
	@Value("${unipock.oss.bucketName:xinglantou-test}")
	private String bucketName;
	@Value("${unipock.oss.imgServer:http://xinglantou-test.img-cn-shenzhen.aliyuncs.com}")
	private String imgServer;
	// @Autowired
	// private ResourceServiceImpl resourceService;

	/*
	 * @RequestMapping(value = "/method2", method = RequestMethod.POST)
	 * 
	 * @ResponseBody public String method2(@RequestParam MultipartFile file,
	 * 
	 * @RequestParam String messageContent ) {
	 * //多个参数的话只要多个@RequestParam即可，注意参数名要和表单里面的属性名一致 JSONObject json =new
	 * JSONObject(); System.out.println(messageContent); String
	 * orgiginalFileName = ""; int m =new Random().nextInt(100)+10;
	 * System.out.println("m="+m); String path="C:\\Tools\\"+m+"b.txt"; try {
	 * File newFile =new File(path); file.transferTo(newFile);
	 * 
	 * String fileName = file.getName(); // InputStream inputStream =
	 * file.getInputStream(); String content = file.getContentType();
	 * orgiginalFileName = file.getOriginalFilename(); System.out.println(
	 * "fileName: "+fileName+", inputStream: "+ "" +"\r\n content: "+content+
	 * ", orgiginalFileName: ="+ orgiginalFileName +"\r\n projectName: "); }
	 * catch (IOException e) { e.printStackTrace(); } json.put("flag", true);
	 * json.put("message", "success"); System.out.println(json.toJSONString());
	 * return json.toJSONString(); }
	 */

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public ExecuteResult<String> upload(HttpServletRequest request) {
		logger.debug("enter the oss upload method!");
		try {
			List<MultipartFile> files = ((MultipartRequest) request).getFiles("upfile");
			List<String> collect = files.stream().map(file -> saveImage(file)).collect(Collectors.toList());
			logger.debug("****图片保存成功****");
			return ExecuteResult.ok(collect.get(0));
		} catch (Exception e) {
			logger.error("图片上传出错，", e);
			return ExecuteResult.fail(1, "图片上传失败,请联系系统管理员");

		}
	}

	public String saveImage(MultipartFile file) {

		try {
			if (!file.isEmpty()) {
				logger.debug("****开始保存图片****");
				String type = null;// 文件类型
				String path = null; //文件路径
				String fileName = file.getOriginalFilename();// 文件原名称
				System.out.println("上传的文件原名称:" + fileName);
				// 判断文件类型
				type = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
				if (type == null) {// 判断文件类型是否为空
					logger.error("文件为空!");
					return null;
				}
				if (".GIF".equals(type.toUpperCase()) || ".PNG".equals(type.toUpperCase())
						|| ".JPG".equals(type.toUpperCase())) {
					path = this.path + DateUtil.date2Nanoseconds(new Date()) + type;
					File newFile = new File(path);
					// 转存文件到指定的路径
  					file.transferTo(newFile);

				} else
					logger.debug("****不是图片类型****");
			} else
				logger.debug("****后缀名为空****");
		} catch (Exception e) {
			logger.error("保存图片失败!", e);
		}

		return path;

	}

	@RequestMapping(value = "/multipartUpload", method = RequestMethod.POST)
	@ResponseBody
	public ExecuteResult<String[]> multipartUpload(HttpServletRequest request) {
		logger.debug("enter the oss upload method!");
		try {
			List<MultipartFile> files = ((MultipartRequest) request).getFiles("upfile");
			/*
			 * List<ResourceBO> resourceList = files.stream().map(file
			 * ->ossUpload(file)) .collect(Collectors.toList()); String[]
			 * urlArray=new String[resourceList.size()]; for(int
			 * i=0;i<urlArray.length;i++) {
			 * urlArray[i]=resourceList.get(i).getUrl(); }
			 */
			// List<Resource> resourceList = Stream.of(files).map(file
			// ->ossUpload(file))
			// .collect(Collectors.toList());
			// ObjectCollectionResponse<ResourceBO> result = new
			// ObjectCollectionResponse<>(0, "图片上传成功", resourceList);
			// return ExecuteResult.ok(resourceList.get(0).getUrl());
			// return ExecuteResult.ok(urlArray);
			return null;
		} catch (Exception e) {
			logger.error("图片上传出错，", e);
			return ExecuteResult.fail(1, "图片上传失败,请联系系统管理员");
			// return new ObjectCollectionResponse<>(-1, "图片上传失败,请联系系统管理员");
		}
	}

	// @RequestMapping(value = "/picupload", method = RequestMethod.POST)
	// @ResponseBody
	// public ObjectCollectionResponse<ResourceBO> upload(@RequestParam("files")
	// MultipartFile[] files) {
	// logger.debug("enter the oss upload method!");
	// try {
	//// List<MultipartFile> f = ((MultipartHttpServletRequest)
	// request).getFiles("upfile");
	// List<ResourceBO> resourceList =
	// ((List<MultipartFile>)Collections.arrayToList(files)).stream().map(file
	// ->ossUpload(file))
	// .collect(Collectors.toList());
	//// List<Resource> resourceList = Stream.of(files).map(file
	// ->ossUpload(file))
	//// .collect(Collectors.toList());
	// ObjectCollectionResponse<ResourceBO> result = new
	// ObjectCollectionResponse<>(0, "", resourceList);
	// return result;
	// } catch (Exception e) {
	// logger.error("图片上传出错，", e);
	// return new ObjectCollectionResponse<>(-1, "图片上传失败,请联系系统管理员");
	// }
	// }

	public String ossUpload(MultipartFile file) {
		try {
			if (!file.isEmpty()) {
				logger.debug("file size = " + file.getSize());
				OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
				ossClient.createBucket(bucketName);
				InputStream content = file.getInputStream();

				// 创建上传Object的Metadata
				ObjectMetadata meta = new ObjectMetadata();
				// 必须设置ContentLength
				meta.setContentLength(file.getSize());

				// 设置文件名
				String type = "";
				if (file.getOriginalFilename().indexOf(".") >= 0) {
					type = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
				}
				int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
				String dir = Calendar.getInstance().get(Calendar.YEAR) + "";
				if (month < 10) {
					dir += "0" + month;
				} else {
					dir += month;
				}
				String key = dir + "/" + DateUtil.date2Nanoseconds(new Date()) + type;

				// 上传Object.
				PutObjectResult result = ossClient.putObject(bucketName, key, content, meta);

				logger.debug("result==" + result.getETag());

				Calendar ca = Calendar.getInstance();
				ca.add(Calendar.YEAR, 100);
				ca.getTime();

				// 获得OSS服务器URL
				URL url = ossClient.generatePresignedUrl(bucketName, key, ca.getTime());
				logger.info("url:" + url);
				String strUrl = url.toString();
				content.close();
				OSSObject object = ossClient.getObject(bucketName, key);
				object.getObjectContent().close();
				// 将图片上传记录保存到本地
				if (strUrl.indexOf("?") > -1) {
					strUrl = strUrl.substring(0, strUrl.indexOf("?"));
				}
				strUrl = imgServer + strUrl.substring(strUrl.indexOf('/', 10));
				// ResourceBO resource = new ResourceBO();
				// resource.setUrl(strUrl);
				// resource.setKey(key);
				// resource.setSize(Double.valueOf(file.getSize()));
				// resourceService.add(resource);
				// logger.debug("生成图片上传对象" + resource);
				// return resource;
				return null;
			} else {
				return null;
			}
		} catch (Exception e) {
			logger.error("上传失败!", e);
			return null;
		}
	}

	// @RequestMapping(value = "/deletePic")
	// @ResponseBody
	// public String deletePic(@RequestBody JSONObject jsonObject,
	// HttpServletResponse response) {
	// logger.info("enter the oss delete method!");
	// JSONObject returnJson = new JSONObject();
	// try {
	// bucketName = sysParamService.getValue("bucketName");
	// accessKeyId = sysParamService.getValue("accessKeyId");
	// accessKeySecret = sysParamService.getValue("accessKeySecret");
	// endPoint = sysParamService.getValue("endPoint-https");
	// if (StringUtils.isNotBlank(jsonObject.getString("key"))) {
	//
	// OSSClient ossClient = new OSSClient(endPoint, accessKeyId,
	// accessKeySecret);
	// ossClient.deleteObject(bucketName, jsonObject.getString("key"));
	//
	// ossClient.shutdown();
	// }
	// } catch (Exception e) {
	// logger.error("删除图片出错，", e);
	// return null;
	// }
	// return returnJson.toJSONString();
	// }

	// @RequestMapping(value = "/download")
	// @ResponseBody
	// public JSONObject download(@RequestBody JSONObject requestJson,
	// HttpServletRequest request,
	// HttpServletResponse response) throws IOException {
	// JSONObject jsonReturn = new JSONObject();
	// bucketName = sysParamService.getValue("bucketName");
	// accessKeyId = sysParamService.getValue("accessKeyId");
	// accessKeySecret = sysParamService.getValue("accessKeySecret");
	// endPoint = sysParamService.getValue("endPoint");
	// int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
	// String dir = Calendar.getInstance().get(Calendar.YEAR) + "";
	// if (month < 10) {
	// dir += "0" + month;
	// } else {
	// dir += month;
	// }
	// try {
	// logger.info(" array =" + requestJson.getJSONArray("url"));
	// logger.info("size " + requestJson.getJSONArray("url").size());
	// JSONArray array = requestJson.getJSONArray("url");
	//
	// String[] strs = new String[array.size()];
	// for (int i = 0; i < array.size(); i++) {
	// logger.info("url" + i + "=" + array.get(i).toString());
	// URL url = new URL(array.get(i).toString());
	// HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	// // 设置超时间为3秒
	// conn.setConnectTimeout(3 * 1000);
	// // 防止屏蔽程序抓取而返回403错误
	// conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;
	// Windows NT; DigExt)");
	//
	// // 得到输入流
	// InputStream inputStream = conn.getInputStream();
	// byte[] buffer = new byte[1024];
	// int len = 0;
	// ByteArrayOutputStream bos = new ByteArrayOutputStream();
	// while ((len = inputStream.read(buffer)) != -1) {
	// bos.write(buffer, 0, len);
	// }
	// bos.close();
	// // 获取自己数组
	// byte[] getData = bos.toByteArray();
	// // 文件保存位置
	// File saveDir = new File("/downloadpic");
	// if (!saveDir.exists()) {
	// saveDir.mkdir();
	// }
	// // URL根据'/'截取，获取最后一个为文件名
	// // String files[] = array.get(i).toString().split("/");
	// String fileName = DateUtil.date2Str(new Date(), new
	// SimpleDateFormat("yyyyMMddHHmmssSSS"));
	// File file = new File(saveDir + File.separator + fileName);
	// logger.info("path:" + file.getAbsolutePath());
	// FileOutputStream fos = new FileOutputStream(file);
	// fos.write(getData);
	// if (fos != null) {
	// fos.close();
	// }
	// if (inputStream != null) {
	// inputStream.close();
	// }
	//
	// OSSClient ossClient = new OSSClient(endPoint, accessKeyId,
	// accessKeySecret);
	// ossClient.createBucket(bucketName);
	// InputStream content = new FileInputStream(file);
	//
	// // 创建上传Object的Metadata
	// ObjectMetadata meta = new ObjectMetadata();
	// // 必须设置ContentLength
	// meta.setContentLength(file.length());
	//
	// // 设置文件名
	// String type = "";
	// if (file.getName().indexOf(".") >= 0) {
	// type = file.getName().substring(file.getName().indexOf("."));
	// }
	//
	// String key = dir + "/" + DateUtil.date2Str(new Date(), new
	// SimpleDateFormat("yyyyMMddHHmmssSSS"))
	// + type;
	//
	// // 上传Object.
	// PutObjectResult result = ossClient.putObject(bucketName, key, content,
	// meta);
	//
	// logger.debug("result==" + result.getETag());
	//
	// Calendar ca = Calendar.getInstance();
	// ca.add(Calendar.YEAR, 100);
	// ca.getTime();
	//
	// // 获得OSS服务器URL
	// URL urlOss = ossClient.generatePresignedUrl(bucketName, key,
	// ca.getTime());
	// logger.info("url:" + urlOss);
	// String strUrl = urlOss.toString();
	// content.close();
	// OSSObject object = ossClient.getObject(bucketName, key);
	// object.getObjectContent().close();
	//
	// if (strUrl.indexOf("?") > -1) {
	// strs[i] = strUrl.substring(0, strUrl.indexOf("?"));
	// } else {
	// strs[i] = urlOss.toString();
	// }
	// }
	// jsonReturn.put("data", strs);
	// jsonReturn.put("code", 0);
	// jsonReturn.put("msg", "成功");
	// } catch (Exception e) {
	// logger.error("图片下载上传出错：", e);
	// return null;
	// }
	// return jsonReturn;
	// }

	public String getAccessKeyId() {
		return accessKeyId;
	}

	public void setAccessKeyId(String accessKeyId) {
		this.accessKeyId = accessKeyId;
	}

	public String getAccessKeySecret() {
		return accessKeySecret;
	}

	public void setAccessKeySecret(String accessKeySecret) {
		this.accessKeySecret = accessKeySecret;
	}

	public String getEndPoint() {
		return endPoint;
	}

	public void setEndPoint(String endPoint) {
		this.endPoint = endPoint;
	}

	public String getBucketName() {
		return bucketName;
	}

	public void setBucketName(String bucketName) {
		this.bucketName = bucketName;
	}

	public String getImgServer() {
		return imgServer;
	}

	public void setImgServer(String imgServer) {
		this.imgServer = imgServer;
	}

	public static void main(String[] args) {
		// 1. Individual values
		Stream<String> stream = Stream.of("a", "b", "c");
		// 2. Arrays
		String[] strArray = new String[] { "a", "b", "c" };
		stream = Stream.of(strArray);
		stream = Arrays.stream(strArray);
		// 3. Collections
		List<String> list = Arrays.asList(strArray);
		stream = list.stream();
		stream.map(String::toUpperCase).forEach(System.out::println);
	}
}